Skip to main content

Range Sum Query - Immutable

Question

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example 1
Input: nums = [1, 3, 5]
Range: [0, 2]

Output: 9

Solution

all//Range Sum Query - Immutable.py


class NumArray:
def __init__(self, nums):
self.nums = nums
self.sums = [0]
s = 0
for num in nums:
s += num
self.sums.append(s)

def sumRange(self, i, j):
return self.sums[j+1] - self.sums[i]